package cn.edu.sdjzu.xg.eagle.Test;

import cn.edu.sdjzu.xg.eagle.dao.TeacherDaoImpl;
import cn.edu.sdjzu.xg.eagle.dao.UserDaoImpl;
import cn.edu.sdjzu.xg.eagle.entity.Teacher;
import cn.edu.sdjzu.xg.eagle.entity.User;
import cn.edu.sdjzu.xg.eagle.exception.BaseException;
import cn.edu.sdjzu.xg.eagle.util.JdbcHelper;

import java.sql.Connection;
import java.sql.SQLException;

public class TeacherDaoTest {

    private static TeacherDaoTest teacherDaoTest = new TeacherDaoTest();
    private final TeacherDaoImpl teacherDaoImpl = TeacherDaoImpl.getInstance();
    private final UserDaoImpl userDaoImpl = UserDaoImpl.getInstance();

    private TeacherDaoTest() {}

    public static TeacherDaoTest getInstance() {
        return teacherDaoTest;
    }

    public boolean addTeacherWithUser(Teacher teacher)throws SQLException{
        Connection conn = null;
        boolean added = false;
        try {
            conn = JdbcHelper.getConn();
            conn.setAutoCommit(false);

            if(!teacherDaoImpl.addTeacher(teacher,conn)) {
                conn.rollback();
                return false;
            }
            User user = new User(teacher.getName(),teacher.getPassword(),teacher);
            if (!userDaoImpl.addUser(user,conn)) {
                conn.rollback();
                return false;
            }
            added = true;
            conn.commit();
            return added;
        } catch (Exception e) {
            try {
                if(conn != null) {
                    conn.rollback();
                }
            }catch (SQLException se) {
                throw new BaseException("事物回滚失败:" + se.getMessage());
            }
            throw new BaseException("添加失败:" + e.getMessage());
        } finally {
            conn.setAutoCommit(true);
            JdbcHelper.close(conn);
        }
    }

    // TeacherService.java
    public boolean deleteTeacherWithUser(Long id) throws BaseException, SQLException {
        Connection conn = null;
        try {
            conn = JdbcHelper.getConn();
            conn.setAutoCommit(false);

            // 先删除用户
            if (!userDaoImpl.deleteUser(id, conn)) {
                conn.rollback();
                return false;
            }

            // 再删除教师
            if (!teacherDaoImpl.deleteTeacher(id, conn)) {
                conn.rollback();
                return false;
            }

            conn.commit();
            return true;
        } catch (SQLException e) {
            if (conn != null) conn.rollback();
            throw new BaseException("删除失败: " + e.getMessage());
        } finally {
            JdbcHelper.close(conn);
        }
    }

}

